import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-09-29
 * Time: 13:04
 */
class Solution13 {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> vis = new HashSet<>();
        Set<String> hash = new HashSet<>();

        for(String x : wordList) {
            hash.add(x);
        }

        // 特殊判断
        if(!hash.contains(endWord)) {
            return 0;
        }

        Queue<String> q = new LinkedList<>();
        q.add(beginWord);
        vis.add(beginWord);

        int step = 1;

        while(!q.isEmpty()) {
            step++;
            int size = q.size();
            while(size-- != 0) {
                String t = q.poll();
                for(int i = 0; i < t.length(); i++) {
                    char[] tmp = t.toCharArray();
                    for(char ch = 'a'; ch <= 'z'; ch++) {
                        tmp[i] = ch;
                        String next = new String(tmp);
                        if(hash.contains(next) && !vis.contains(next)) {
                            if(next.equals(endWord)) {
                                return step;
                            }
                            vis.add(next);
                            q.add(next);
                        }
                    }
                }
            }
        }
        return 0;
    }
}
